<template>
  <gc-dialog
    :title="isEdit ? '编辑角色' : '新增角色'"
    :dialog-visible="true"
    @cancel="handleCancle"
    @ok="handleConfirm"
  >
    <el-form
      ref="formRef"
      label-position="top"
      :model="form"
      :rules="formRules"
    >
      <el-form-item label="角色名称" prop="name">
        <el-input type="text" v-model="form.name"  placeholder="请输入" />
      </el-form-item>
      <el-form-item label="角色状态" prop="status">
        <el-radio-group v-model="form.status" class="ml-4">
          <el-radio label="0">禁用</el-radio>
          <el-radio label="1">启用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </gc-dialog>
</template>

<script setup lang="ts" name="OperateRoleModal">
import { ref, reactive, computed, watch, type PropType } from 'vue'
import { ruleRequired, ruleMaxLength, NAME_CN } from '@/utils/rules'
import type { FormInstance, FormRules } from 'element-plus'
import { apiCreateRole, apiUpdateRole } from '@/http/service'
import { ElMessage } from 'element-plus'
import type { Role } from '@/http/type'

const props = defineProps({
  roleInfo: {
    type: Object as PropType<null | Role>,
    default: () => null
  }
})
const emit = defineEmits(['close-modal'])
const formRef = ref<null | FormInstance>(null)
const form = reactive({
  name: '',
  status: '1'
})
const formRules = reactive<FormRules>({
  name: [ruleRequired('请输入角色名称'), ruleMaxLength(64), NAME_CN],
  status: [ruleRequired('请选择角色状态')]
})
const isEdit = computed(() => {
  return Boolean(props.roleInfo)
})

async function handleConfirm () {
  const valid = await formRef.value?.validate()
  if (valid) {
    const API = isEdit.value ? apiUpdateRole : apiCreateRole
    await API(form)
    ElMessage.success(isEdit.value ? '编辑角色成功' : '新增角色成功')
    emit('close-modal', true)
  }
}

function handleCancle () {
  emit('close-modal')
}

watch(() => props.roleInfo, val => {
  if (val) {
    const { id, name, status } = val
    Object.assign(form, {
      id, name, status
    })
  }
}, { immediate: true })
</script>

<style scoped lang="scss"></style>
